package xyz.xcvu.ma2.module;


import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.annotation.MagicModule;

import java.io.File;
import java.lang.reflect.Method;

@Component
@MagicModule("ip")
public class IpUtil {

    private static final Log log = LogFactory.get();
    private static final String dbPath = System.getProperty("user.dir")+"/db/ip2region.db";

    public String getCityInfo(String ip){
        // db文件下载地址，https://gitee.com/lionsoul/ip2region/tree/master/data 下载下来后解压，db文件在data目录下
        // String dbPath = System.getProperty("user.dir")+"/db/ip2region.db";
        File file = new File(dbPath);
        if (file.exists() == false) {
            log.error("数据库文件不存在");
            return null;
        }

        //查询算法 B-tree
        int algorithm = DbSearcher.BTREE_ALGORITHM;
        try {
            DbConfig config = new DbConfig();
            DbSearcher searcher = new DbSearcher(config, dbPath);
            Method method = null;
            switch (algorithm) {
                case DbSearcher.BTREE_ALGORITHM:
                    method = searcher.getClass().getMethod("btreeSearch", String.class);
                    break;
                case DbSearcher.BINARY_ALGORITHM:
                    method = searcher.getClass().getMethod("binarySearch", String.class);
                    break;
                case DbSearcher.MEMORY_ALGORITYM:
                    method = searcher.getClass().getMethod("memorySearch", String.class);
                    break;
            }
            if (Util.isIpAddress(ip) == false) {
                log.error("IP地址解析错误!");
                return null;
            }
            DataBlock dataBlock = (DataBlock) method.invoke(searcher, ip);
            return dataBlock.getRegion();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }
}
